﻿from django.db import models, backend
from django.db import connection 
from django.contrib.auth.models import User

class SearchManager(models.Manager):
    use_for_related_fields = True
    def __init__(self):
        super(SearchManager, self).__init__()

    def search(self, query):
        cursor = connection.cursor()
        cursor.execute("""
            SELECT (MATCH(t.summary, t.description) AGAINST ('%s')) AS relevance, 
            t.id, 
            t.serial, 
            t.project_id, 
            t.kind, 
            t.summary, 
            t.description, 
            t.status, 
            t.resolution, 
            t.reporter_id, 
            u.username, 
            t.severity, 
            t.severityorder, 
            t.reportdate 
            FROM bugs_task t, auth_user u  
            WHERE MATCH(t.summary, t.description) AGAINST ('%s') 
            AND t.owner_id=u.id
            ORDER BY t.severityorder DESC, t.kind ASC"""  % (query, query))
        result_list = []
        for row in cursor.fetchall():            
            p = self.model(id=row[1],serial=row[2],kind=row[4],summary=row[5],description=row[6],status=row[7],resolution=row[8],owner=User(username=row[10]),severity=row[11],severityorder=row[12],reportdate=row[13],)
            p.relevance = row[0]
            result_list.append(p)
        return result_list
    